import wx from '../../subwe/bridge';
import WXPage from "../../subwe/page";
import { openBluetoothAdapter, openBluetoothAdapterPeripheral } from '../../utils/bluetooth';
import CONST from "../../utils/const";
const app = getApp();
import { Index } from '../../apis/index';
import util from '../../utils/util';
const API = new Index();
WXPage({
  data: {
    placeId: 0,
    deviceSn: '',
    bluetoothMac: '',
    loginInfo: wx.getStorageSync('login_key'),
    pageNum: 1,
    pageSize: 10,
    dataList: [],
    showMoreVisable: false,
    imgUrl: '',
    defaultImg: '/static/zhongman2/img_Coupon@2x.png',
    host: wx.getStorageSync("host"),
    bluetoothStatus: CONST.BluetoothStatusSearch,
    bluetoothErr: {}
  },
  onLoad(options) {
    this.setData({
      loginInfo: wx.getStorageSync('login_key')
    });
    this.setData({
      host: wx.getStorageSync("host")
    });
    this.setData({
      placeId: Number(options.placeId) || 0
    });
    this.setData({
      deviceSn: options.deviceSn || ''
    });
    this.setData({
      bluetoothMac: options.mac || ''
    });
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#FFFFFF'
    });
    this.openBluetoothAdapter(this.data.bluetoothMac, this.data.deviceSn);
    this.setData({
      imgUrl: util.IMG_URL
    });
    this.getGoodsList(this.data.pageNum);
  },
  serviceCall() {
    wx.makePhoneCall({
      phoneNumber: util.ZM_PHONE_NUMBER
    });
  },
  openBluetoothAdapter(bluetoothMac, deviceSn) {
    this.setData({
      bluetoothStatus: CONST.BluetoothStatusSearch
    });
    openBluetoothAdapter({
      deviceSn,
      bluetoothMac,
      success: res => {
        this.setData({
          bluetoothStatus: CONST.BluetoothStatusSuccess
        });
      },
      fail: err => {
        console.log(err);
        this.setData({ bluetoothStatus: CONST.BluetoothStatusFail, bluetoothErr: err });
        // this.connectionBluetoothStatusOff()
      }
    });
  },
  connectionBluetoothStatusOff() {
    if (this.data.bluetoothStatus === CONST.BluetoothStatusSuccess) return true;
    wx.showModal({
      title: '蓝牙连接失败',
      content: `${this.data.bluetoothErr.errorMessage || '查看蓝牙连接教程'}`,
      confirmText: '查看教程',
      cancelText: '重新连接',
      cancelColor: '#333',
      confirmColor: '#00A49A',
      success(res) {
        if (res.confirm) wx.navigateTo({
          url: `/pages/padlineBlue/padline?showErr=1`
        });
      },
      complete: (res)=> {
        if(res.confirm || this.data.bluetoothStatus === CONST.BluetoothStatusSuccess) return
        console.log('手动重试', res)
        this.openBluetoothAdapter(this.data.bluetoothMac, this.data.deviceSn)
      },
    });
    return false;
  },
  // 售货下单
  createAutomate(ev) {
    console.log(ev.target.dataset)
    ev.mark =  ev.target.dataset
    if (ev.mark.goodsInfo.status !== 1) return wx.showToast({
      title: '己售罄',
      icon: 'none'
    });
    if (!this.connectionBluetoothStatusOff()) return;
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let openid = this.data.loginInfo.openid;
    let param = {
      deviceSn: this.data.deviceSn,
      routesId: ev.mark.goodsInfo.routesId,
      openid
    };
    API.automateCreateGoodsOrder(param).then(res => {
      if (!res.result) {
        wx.hideLoading();
        wx.showToast({
          title: '下单失败',
          icon: 'none'
        });
        return;
      }
      this.wxPayment(res.result, ev.mark.goodsInfo);
    });
  },
  // 微信支付
  wxPayment: function (data, goodsInfo) {

    let { out_trade_no, trade_no } = data.AliPayTradeCreateResBody || {}
    my.tradePay({
      tradeNO: out_trade_no,
      success: (res) => {
        wx.hideLoading();
        console.log("wxPayment-success", res);
        if(Number(res.resultCode) === 9000) return this.automateShippingGoodsAdvice(trade_no, goodsInfo.routesId)
        wx.showToast({title: res.memo || '支付失败', icon: 'none'})
      },
      fail: (res) => {
        wx.hideLoading()
        console.log("fail info", res);
        wx.showToast({
          title: '支付中断',
          icon: 'none'
        });
      }
    });

    // const param = JSON.parse(data);
    // wx.requestPayment({
    //   timeStamp: param.timeStamp,
    //   nonceStr: param.nonceStr,
    //   package: param.package,
    //   signType: param.signType,
    //   paySign: param.paySign,
    //   success: res => {
    //     wx.hideLoading();
    //     console.log("wxPayment-success", res);
    //     this.automateShippingGoodsAdvice(param.tradeNo, goodsInfo.routesId);
    //   },
    //   fail(res) {
    //     wx.hideLoading();
    //     console.log("fail info", res);
    //     wx.showToast({
    //       title: '支付中断',
    //       icon: 'none'
    //     });
    //   }
    // });
  },
  // 发货通知 ZM20220518113149323684
  automateShippingGoodsAdvice(tradeNo, routesId) {
    API.automateShippingGoodsAdvice({
      tradeNo
    }).then(res => {
      if (!res.result) return wx.showModal({
        title: '出货失败',
        content: '出货失败，请重试',
        confirmText: '立即重试',
        showCancel: false,
        success: res => {
          this.automateShippingGoodsAdvice(tradeNo, routesId);
        }
      });
      this.getGoodsList(1);
      this.openDeliveryChannel(routesId);
    });
  },
  // 打开出货通道
  openDeliveryChannel(routesId) {
    openBluetoothAdapterPeripheral({
      bluetoothMac: this.data.bluetoothMac,
      type: routesId === 1 ? CONST.BluetoothTypeStartChannelOne : CONST.BluetoothTypeStartChannelTwo,
      success: res => {
        console.log('startAdvertising', res);
      },
      fail: err => {
        console.log('startAdvertising-err', err);
        wx.showModal({
          title: '出货失败',
          content: '出货失败，请重试',
          confirmText: '立即重试',
          showCancel: false,
          success: res => {
            this.openDeliveryChannel(routesId);
          }
        });
      }
    });
  },
  getGoodsList: function (pageNum) {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    var param = {
      pageNo: pageNum,
      pageSize: this.data.pageSize,
      placeId: this.data.placeId,
      deviceSn: this.data.deviceSn
    };
    if (param.pageNo === 1) this.data.dataList = [];
    API.getAutomateGoodsList(param).then(res => {
      wx.hideLoading();
      var dataList = this.data.dataList.concat(res.result.data);
      var showMore = false;
      var stockList = [];
      // 如果库存为空则不展示
      for (var i = 0; i < dataList.length; i++) {
        if (dataList[i].num > 0) {
          stockList.push(dataList[i]);
        }
      }
      if (res.result.totalCount > dataList.length) {
        showMore = true;
      }
      this.setData({
        index: i,
        showMoreVisable: showMore,
        stockList: stockList,
        host: res.result.host
      });
    });
  },
  // 跳转详情
  goodsDeatail(e) {
    wx.navigateTo({
      url: '/pages/evaluateGift/myPrice/myPrice?id=' + e.mark.id
    });
  },
  // 显示更多
  showMore: function () {
    var pageNum = this.data.pageNum += 1;
    this.getGoodsList(pageNum);
  },
  toKeFu: function () {
    // wx.reportEvent("event_hp_kf", {});
    wx.navigateTo({
      url: '/pages/mine/zmKf/zmkf'
    });
  }
});
